package com.skill.shareskill.activity;

import android.content.Intent;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.util.Log;
import android.view.View;
import android.view.WindowManager;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.Toast;
import cn.smssdk.EventHandler;
import cn.smssdk.SMSSDK;
import com.skill.shareskill.R;
import com.skill.shareskill.service.LoginService;
import com.skill.shareskill.service.RegisteService;

import android.os.Handler;
import android.os.Message;
import android.text.TextUtils;

import static cn.smssdk.SMSSDK.getSupportedCountries;
import static cn.smssdk.SMSSDK.getVerificationCode;
import static cn.smssdk.SMSSDK.submitVerificationCode;

public class RegisteActivity extends AppCompatActivity implements View.OnClickListener {
    private final String TAG="--MainActivity--";
    //app key和app secret 需要填自己应用的对应的！这里只是我自己创建的应用。
    private final String appKey="2761f0144f054";
    private final String appSecret="11b958d2d6a03e082eca3c3982bdd673";
    private EventHandler eh;
    private Handler handler=new Handler(){
        @Override
        public void handleMessage(Message msg) {
            switch (msg.arg1) {
                case 4:
                    //客户端验证成功，可以进行注册,返回校验的手机和国家代码phone/country
                    Toast.makeText(RegisteActivity.this, msg.obj.toString(), Toast.LENGTH_SHORT).show();
                    new Thread(){
                        public void run(){
                            final String result= RegisteService.RegisteByClientPost(phone,psw);
                            if (result!=null){
                                runOnUiThread(new Runnable() {
                                    @Override
                                    public void run() {
                                        String phone=null;
                                        String password=null;
                                        String type=null;
                                        Toast.makeText(RegisteActivity.this,result,Toast.LENGTH_LONG).show();
                                        try {
                                            if (result.equals("1")) {
                                                Toast.makeText(RegisteActivity.this, "注册成功！", Toast.LENGTH_LONG).show();

                                                Intent intent = new Intent(RegisteActivity.this, LoginActivity.class);
                                                startActivity(intent);
                                                finish();
                                            }
                                            if(result.equals("0")){
                                                Toast.makeText(RegisteActivity.this, "该手机号已注册，请直接登录！", Toast.LENGTH_LONG).show();
                                            }
                                        } catch (Exception e) {
                                            // TODO Auto-generated catch block
                                            e.printStackTrace();
                                        }

                                    }
                                });
                            }
                            else{
                                runOnUiThread(new Runnable() {
                                    @Override
                                    public void run() {
                                        Toast.makeText(RegisteActivity.this,"请求失败",Toast.LENGTH_LONG).show();
                                    }
                                });
                            }
                        };

                    }.start();
                    break;
                case 5:
                    //获取验证码成功
                    Toast.makeText(RegisteActivity.this, msg.obj.toString(), Toast.LENGTH_SHORT).show();
                    break;
                case 6:
                    //返回支持发送验证码的国家列表
                    Toast.makeText(RegisteActivity.this, msg.obj.toString(), Toast.LENGTH_SHORT).show();
                    break;
            }
        }
    };
    private TextView tv_lya;
    private Button bt_rcf;
    private EditText et_phone;
    private EditText et_code;
    private EditText et_pa;
    private EditText et_cpa;
    //手机号码
    private String phone;
    //验证码
    private String code;
    private String psw;
    private String psw2;
    private boolean isChange;
    //控制按钮样式是否改变
    private boolean tag = true;
    //每次验证请求需要间隔60S
    private int i=60;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN, WindowManager.LayoutParams.FLAG_FULLSCREEN);
        setContentView(R.layout.registe);
        et_code=findViewById(R.id.et_ryan);
        et_phone=findViewById(R.id.et_rname);
        et_pa=findViewById(R.id.et_rpass);
        et_cpa=findViewById(R.id.et_cfpass);
        // 启动短信验证sdk
        //SMSSDK.initSDK(this, appKey, appSecret);
        eh=new EventHandler(){
            @Override
            public void afterEvent(int event, int result, Object data) {
                if (result == SMSSDK.RESULT_COMPLETE) {
                    //回调完成
                    if (event == SMSSDK.EVENT_SUBMIT_VERIFICATION_CODE) {
                        //提交验证码成功
                        Message msg = new Message();
                        msg.arg1 = 4;
                        msg.obj = data;
                        handler.sendMessage(msg);
                        Log.d(TAG, "提交验证码成功");
                    } else if (event == SMSSDK.EVENT_GET_VERIFICATION_CODE) {
                        Message msg = new Message();
                        //获取验证码成功
                        msg.arg1 = 5;
                        msg.obj = "获取验证码成功";
                        handler.sendMessage(msg);
                        Log.d(TAG, "获取验证码成功");
                    } else if (event == SMSSDK.EVENT_GET_SUPPORTED_COUNTRIES) {
                        Message msg = new Message();
                        //返回支持发送验证码的国家列表
                        msg.arg1 = 6;
                        msg.obj = "返回支持发送验证码的国家列表";
                        handler.sendMessage(msg);
                        Log.d(TAG, "返回支持发送验证码的国家列表");
                    }
                } else {
                    Message msg = new Message();
                    //返回支持发送验证码的国家列表
                    msg.arg1 = 7;
                    msg.obj = "验证失败";
                    handler.sendMessage(msg);
                    Log.d(TAG, "验证失败");
                    ((Throwable) data).printStackTrace();
                }
            }
        };
        SMSSDK.registerEventHandler(eh); //注册短信回调

        tv_lya= (TextView) findViewById(R.id.tv_ryan);
        tv_lya.setClickable(false);
        bt_rcf= (Button) findViewById(R.id.bt_rcf);
        tv_lya.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                //获取验证码操作
                phone=et_phone.getText().toString();
                if(phone.equals("")){
                    Toast.makeText(RegisteActivity.this,"手机号不能为空",Toast.LENGTH_SHORT).show();
                }else{
                    //填写了手机号码
                    if(isMobileNO(phone)){
                        //如果手机号码无误，则发送验证请求
                        tv_lya.setClickable(true);
                        changeBtnGetCode();
                        getSupportedCountries();
                        getVerificationCode("86", phone);
                    }else{
                        //手机号格式有误
                        Toast.makeText(RegisteActivity.this,"手机号格式错误，请检查",Toast.LENGTH_SHORT).show();
                    }
                }
            }
        });
        bt_rcf.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                //验证操作
                code=et_code.getText().toString();
                psw=et_pa.getText().toString();
                psw2=et_cpa.getText().toString();
                if(psw.equals("")){
                    Toast.makeText(RegisteActivity.this,"密码不能为空",Toast.LENGTH_SHORT).show();
                }
                else if(psw2.equals("")){
                    Toast.makeText(RegisteActivity.this,"确认密码不能为空",Toast.LENGTH_SHORT).show();
                }
                else if(!psw.equals(psw2)){
                    Toast.makeText(RegisteActivity.this,"两次密码不一致",Toast.LENGTH_SHORT).show();
                }
                else if (code.equals("")){
                    Toast.makeText(RegisteActivity.this,"验证码不能为空",Toast.LENGTH_SHORT).show();
                }else{
                    //填写了验证码，进行验证
                    submitVerificationCode("86", phone, code);
                }
            }
        });
    }
    private void changeBtnGetCode() {
        Thread thread = new Thread() {
            @Override
            public void run() {
                if (tag) {
                    while (i > 0) {
                        i--;
                        //如果活动为空
                        if (RegisteActivity.this == null) {
                            break;
                        }
                        RegisteActivity.this.runOnUiThread(new Runnable() {
                            @Override
                            public void run() {
                                tv_lya.setText("获取验证码(" + i + ")");
                                tv_lya.setClickable(false);
                            }
                        });
                        try {
                            Thread.sleep(1000);
                        } catch (InterruptedException e) {
                            e.printStackTrace();
                        }
                    }
                    tag = false;
                }
                i = 60;
                tag = true;
                if (RegisteActivity.this != null) {
                    RegisteActivity.this.runOnUiThread(new Runnable() {
                        @Override
                        public void run() {
                            tv_lya.setText("获取验证码");
                            tv_lya.setClickable(true);
                        }
                    });
                }
            }
        };
        thread.start();
    }
    private boolean isMobileNO(String phone) {
       /*
    移动：134、135、136、137、138、139、150、151、157(TD)、158、159、187、188
    联通：130、131、132、152、155、156、185、186
    电信：133、153、180、189、（1349卫通）
    总结起来就是第一位必定为1，第二位必定为3或5或8，其他位置的可以为0-9
    */
        String telRegex = "[1][358]\\d{9}";//"[1]"代表第1位为数字1，"[358]"代表第二位可以为3、5、8中的一个，"\\d{9}"代表后面是可以是0～9的数字，有9位。
        if (TextUtils.isEmpty(phone)) return false;
        else return phone.matches(telRegex);
    }
    public void onClick(View v) {
    }
    public void Finish(View view){
        finish();
    }
}
